// 导入需要的组件和资源
import { Button, Space, Empty, Toast } from "@nutui/nutui-react";
import React, { useEffect, useState } from "react";
import { useSelector } from 'react-redux';
import { api } from '@/api/api';
import { formatPrice } from '@/utils/formatPrice';
import { truncateProductDescription } from '@/utils/truncateText';
import time from "@assets/images/time.png";
import noData from "@/assets/images/no-data.png";
import './HotService.less';

const HotService = () => {
  const shopId = useSelector(state => state.shop.shopId);
  const userInfo = useSelector(state => state.user.userInfo);
  const [hotGoods, setHotGoods] = useState([]);
  const [loading, setLoading] = useState(false);
  const [addingToCart, setAddingToCart] = useState({});

  const fetchRecommendedProducts = async () => {
    try {
      setLoading(true);
      const currentShopId = shopId || localStorage.getItem("shop_id");
      if (currentShopId) {
        const response = await api.getRecommendedProducts({ shopId: currentShopId });
        if (response.data && response.code === 200) {
          setHotGoods(response.data);
        }
      }
    } catch (error) {
      console.error('获取热门推荐产品失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 添加商品到购物车
  const handleAddToCart = async (product) => {
    if (!userInfo || !userInfo.userId) {
      Toast.show('请先登录');
      return;
    }
    const productId = product.productId;
    setAddingToCart(prev => ({ ...prev, [productId]: true }));
    try {
      const response = await api.addToCart({
        shopId,
        userId: userInfo.userId,
        productId: productId,
        quantity: 1
      });
      if (response.code === 200) {
        Toast.show('已添加到购物车');
      } else {
        Toast.show('添加失败，请重试');
      }
    } catch (error) {
      Toast.show('添加失败，请重试');
    } finally {
      setAddingToCart(prev => ({ ...prev, [productId]: false }));
    }
  };

  useEffect(() => {
    fetchRecommendedProducts();
  }, []);

  return (
    <Space direction="vertical">
      {loading ? (
        <div className="loading-container">加载中...</div>
      ) : hotGoods.length ? (
        hotGoods.map((item, index) => {
          return (
            <div key={index} className="card-container flex-row">
              <img 
                src={item.productImgUrl} 
                alt={item.productName} 
                className="product-image"
              />
              <div className="card-info flex-column">
                <div className="card-info-title flex-row">
                  <span className="product-name">
                    {item.productName}
                  </span>
                </div>
                <span className="product-description">
                  {truncateProductDescription(item.productDescription)}
                </span>
                <div className="card-info-price flex-row">
                  <div className="price-container">
                    <span className="product-price">
                      {formatPrice(item.productPrice)}
                    </span>
                  </div>
                </div>
                {/* {item.productGroupId === 1 && (
                  <div className="time-container flex-row">
                    <img src={time} alt="time" className="time-icon" />
                    <span>120分钟</span>
                  </div>
                )}  */}
              </div>  
              <Button 
                size="small" 
                type="primary"
                loading={addingToCart[item.productId]}
                onClick={() => handleAddToCart(item)}
                className="add-to-cart-button"
              >
                {addingToCart[item.productId] ? '添加中...' : '立即下单'}
              </Button>
            </div>
          );
        })
      ) : (
        <Empty
          image={<img src={noData} alt="" />}
          description="暂无数据"
          className="empty-container"
        />
      )}
    </Space>
  );
};

export default HotService;
